package com.ixuea.courses.mycloudmusicapisp.advice;

import com.ixuea.courses.mycloudmusicapisp.domain.response.Response;
import com.ixuea.courses.mycloudmusicapisp.exception.CommonException;
import com.ixuea.courses.mycloudmusicapisp.exception.NotFoundException;
import com.ixuea.courses.mycloudmusicapisp.util.Constant;
import com.ixuea.courses.mycloudmusicapisp.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.sql.SQLIntegrityConstraintViolationException;

import static com.ixuea.courses.mycloudmusicapisp.util.Constant.ERROR_NOT_FOUND;
import static com.ixuea.courses.mycloudmusicapisp.util.Constant.ERROR_NOT_FOUND_MESSAGE;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class ExceptionHandlerAdvice {

    /**
     * 日志实例
     */
    private static final Logger log = LoggerFactory.getLogger(ExceptionHandlerAdvice.class);


    /**
     * 处理自定义异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = CommonException.class)
    public Response commonException(CommonException exception) {
        //自定义异常

        //获取异常信息
        return ResponseUtil.failed(exception.getStatus(), exception.getMessage(), exception.getDetail());
    }

    /**
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = {DuplicateKeyException.class, SQLIntegrityConstraintViolationException.class})
    public Response duplicateKeyException(Exception exception) {
        return ResponseUtil.failed(Constant.ERROR_DATA_EXIST, Constant.ERROR_DATA_EXIST_MESSAGE);
    }


    /**
     * 默认异常处理器
     * @param exception
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Response defaultHandleException(Exception exception) {
        //打印日志
        //方便调试
        log.error("defaultHandleException {}", exception);

        //其他异常
        return  ResponseUtil.failed();
    }

    /**
     * 访问了不存在的资源
     * @param exception
     * @return
     */
    @ExceptionHandler(value = {NoHandlerFoundException.class, NotFoundException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Response notFoundException(Exception exception) {
        return ResponseUtil.failed(ERROR_NOT_FOUND, ERROR_NOT_FOUND_MESSAGE);
    }
}